package packed

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/gogf/gf/v2/frame/g"
)

func init() {
	// 注册自定义模板函数
	view := g.View()
	// 注册模板函数
	view.BindFunc("add", Add)
	view.BindFunc("sub", Sub)
	view.BindFunc("contains", Contains)
	view.BindFunc("join", Join)
	view.BindFunc("mod", Mod)
	view.BindFunc("set", Set)
}

// Add 加法函数
func Add(a, b interface{}) int {
	aInt, _ := strconv.Atoi(toString(a))
	bInt, _ := strconv.Atoi(toString(b))
	return aInt + bInt
}

// Sub 减法函数
func Sub(a, b interface{}) int {
	aInt, _ := strconv.Atoi(toString(a))
	bInt, _ := strconv.Atoi(toString(b))
	return aInt - bInt
}

// Mod 取模函数
func Mod(a, b interface{}) int {
	aInt, _ := strconv.Atoi(toString(a))
	bInt, _ := strconv.Atoi(toString(b))
	if bInt == 0 {
		return 0 // 避免除以零错误
	}
	return aInt % bInt
}

// Contains 判断是否包含
func Contains(s, substr string) bool {
	return strings.Contains(s, substr)
}

// Join 连接字符串
func Join(a []string, sep string) string {
	return strings.Join(a, sep)
}

// toString 转换为字符串
func toString(v interface{}) string {
	if v == nil {
		return ""
	}
	return strings.TrimSpace(strconv.FormatInt(toInt64(v), 10))
}

// toInt64 转换为int64
func toInt64(v interface{}) int64 {
	if v == nil {
		return 0
	}
	switch value := v.(type) {
	case int:
		return int64(value)
	case int8:
		return int64(value)
	case int16:
		return int64(value)
	case int32:
		return int64(value)
	case int64:
		return value
	case uint:
		return int64(value)
	case uint8:
		return int64(value)
	case uint16:
		return int64(value)
	case uint32:
		return int64(value)
	case uint64:
		return int64(value)
	case float32:
		return int64(value)
	case float64:
		return int64(value)
	case string:
		result, _ := strconv.ParseInt(value, 10, 64)
		return result
	default:
		i, _ := strconv.ParseInt(fmt.Sprintf("%v", v), 10, 64)
		return i
	}
}

// Set 设置变量值
func Set(m map[string]interface{}, key string, value interface{}) string {
	m[key] = value
	return ""
}
